package com.p2p.backend.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.p2p.backend.Constants;
import com.p2p.backend.command.UserCommand;
import com.p2p.backend.model.BackUser;
import com.p2p.backend.model.Privilege;
import com.p2p.backend.service.BackUserService;
import com.p2p.base.model.Action;
import com.p2p.base.model.BackendUser;
import com.p2p.base.model.Module;
import com.p2p.base.model.Oplog;
import com.p2p.base.util.BasePropertyConfigurer;
import com.p2p.base.util.LoginUtil;
import com.p2p.base.web.controller.BaseController;

@Controller
public class UserLoginController extends BaseController{

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource
	private BackUserService backUserService;

	@RequestMapping(value = "/isLogin")
	public void isLogin(HttpServletRequest request, Model model) {
		Object objectUser = LoginUtil.getCurrentUser();

		if (objectUser == null) {
			model.addAttribute("res", 0);
			model.addAttribute("msg", "未登录");
			return;
		}
		model.addAttribute("res", 1);
		BackendUser user = (BackendUser) objectUser;
		Map<String, Object> data = new HashMap<String, Object>();
		model.addAttribute("data", data);
		data.put("username", user.getUserName());
		data.put("logout_url", BasePropertyConfigurer.getContextProperty("p2p.backend_logout_url"));
		
	}

	@RequestMapping(value = "/data/tree_data1.json")
	public void getMenu(UserCommand userCommand, BindingResult result,
			HttpSession session, Model model) throws IOException {
		Object objectUser = LoginUtil.getCurrentUser();
		BackendUser user = (BackendUser) objectUser;
		List<Map<String, Object>> privilegeList = backUserService
				.findAllByUserId(user.getId());
		List<Map<String, Object>> root = MenuUtil.buildRootList2(privilegeList);
		// translate root
		MenuUtil.translate(root);
		model.addAttribute("data", root);
		model.addAttribute("res", 1);
	}

	/**
	 * 用户密码修改
	 * 
	 * @return
	 */
	@Deprecated
	@RequestMapping(value = "/user/passwordModify.json", method = RequestMethod.GET)
	public String passwordModify(
			@RequestParam(required = false) String password,
			@RequestParam(required = false) String newPassword, Model model,
			HttpServletRequest request, HttpServletResponse response) {
		UserCommand userCommand = new UserCommand();
		userCommand.setPassword(password);
		userCommand.setNewPassword(newPassword);
		Oplog oplog = super.oplog(request);
		oplog.setModule(Module.USER_PASSWORD);
		oplog.setAction(Action.UPDATE);
		oplog.setParams("password="+password+",newPassword="+newPassword);
		try {
			BackUser sessionUser = (BackUser) request.getSession()
					.getAttribute(Constants.SESSION_USERINFO);
			String flag = backUserService.passwordModify(userCommand,
					sessionUser.getId());
			model.addAttribute("flag", flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "json";
	}

	/**
	 * 登录
	 * 
	 * @param result
	 * @return
	 * @throws java.io.IOException
	 */
	@Deprecated
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public void login(UserCommand userCommand, BindingResult result,
			HttpSession session, Model model) throws IOException {
		// new
		// UserCommandValidator(UserCommandValidator.TYPE_LOGIN).validate(userCommand,
		// result);// 后台验证
		if (result.hasErrors()) {
		}
		BackUser user = backUserService.checkLogin(userCommand.getUser());
		if (user == null) {
			result.reject("login.input.error");
		} else {
			// 权限
			List<Privilege> privileList = backUserService
					.findPrivilegeByUserId(user.getId());
			session.setAttribute("session_privilege", privileList);

			session.setAttribute(Constants.SESSION_USERINFO, user);
			model.addAttribute("res", 1);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("username", user.getUserName());
			model.addAttribute("data", data);
		}
	}

	@Deprecated
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(Model model, HttpServletRequest request) {
		request.getSession().removeAttribute(Constants.SESSION_USERINFO);
		return "login";
	}

	@Deprecated
	@RequestMapping(value = "/data/tree_data2.json")
	public void getMenu2(UserCommand userCommand, BindingResult result,
			HttpSession session, Model model) throws IOException {

		Object objectUser = LoginUtil.getCurrentUser();
		if (objectUser != null) {
			BackendUser user = (BackendUser) objectUser;
			List<Privilege> privileList = backUserService
					.findPrivilegeByUserId(user.getId());
			List<Map<String, Object>> root = new ArrayList<Map<String, Object>>();
			root = MenuUtil.buildList(privileList);
			model.addAttribute("data", root);
			model.addAttribute("res", 1);
		}
	}
}
